import Taro from '@tarojs/taro'

// 云函数调用工具类
export class CloudService {
  private static instance: CloudService
  private isInitialized = false

  private constructor() {}

  public static getInstance(): CloudService {
    if (!CloudService.instance) {
      CloudService.instance = new CloudService()
    }
    return CloudService.instance
  }

  // 初始化云开发环境
  public async initCloud(): Promise<void> {
    if (this.isInitialized) {
      return
    }

    try {
      await Taro.cloud.init({
        env: 'cloud1-0gy0oubu178f2550', // 请替换为你的云开发环境ID
        traceUser: true
      })
      this.isInitialized = true
      console.log('云开发环境初始化成功')
    } catch (error) {
      console.error('云开发环境初始化失败:', error)
      throw error
    }
  }

  // 调用云函数
  public async callFunction(name: string, data: any = {}): Promise<any> {
    if (!this.isInitialized) {
      await this.initCloud()
    }

    try {
      const result = await Taro.cloud.callFunction({
        name,
        data
      })
      
      console.log(`云函数 ${name} 调用成功:`, result)
      return result.result
    } catch (error) {
      console.error(`云函数 ${name} 调用失败:`, error)
      throw error
    }
  }

  // 测试云函数
  public async testFunction(params: any = {}): Promise<any> {
    return this.callFunction('test', {
      message: 'Hello from Taro!',
      timestamp: Date.now(),
      ...params
    })
  }

  // 客服云函数
  public async customerServiceFunction(params: any = {}): Promise<any> {
    return this.callFunction('customer-service', {
      action: 'sendGreeting',
      timestamp: Date.now(),
      ...params
    })
  }
}

// 导出单例实例
export const cloudService = CloudService.getInstance() 